import {
  ModalForm,
  ProFormSelect,
  ProFormText,
} from '@ant-design/pro-components';
import { message, Transfer } from 'antd';
import { api } from '@/services/api';
import type { User } from '@/services/generated/models/User';
import { PatchedUserRequest } from '@/services/generated';
import { useEffect, useState } from 'react';
import type { TransferItem } from 'antd/es/transfer';

interface UserFormProps {
  visible: boolean;
  onVisibleChange: (visible: boolean) => void;
  onSuccess: () => void;
  user?: User;
}

const UserForm: React.FC<UserFormProps> = ({
  visible,
  onVisibleChange,
  onSuccess,
  user,
}) => {
  // 角色列表状态
  const [roleList, setRoleList] = useState<TransferItem[]>([]);
  const [selectedRoles, setSelectedRoles] = useState<string[]>([]);
  const [loading, setLoading] = useState(false);

  // 获取所有角色和用户当前角色
  useEffect(() => {
    const fetchRoles = async () => {
      if (visible) {
        setLoading(true);
        try {
          // 获取所有角色
          const roles = await api.accounts.accountsGroupsList();
          setRoleList(roles.map(role => ({
            key: role.id.toString(),
            title: role.name,
            description: role.name,
          })));

          // 如果是编辑模式，获取用户当前角色
          if (user) {
            const userRoles = await api.users.accountsUsersGroupsList({ id: user.id });
            setSelectedRoles(userRoles.map(role => role.id.toString()));
          } else {
            setSelectedRoles([]);
          }
        } catch (error) {
          message.error('获取角色列表失败');
        } finally {
          setLoading(false);
        }
      }
    };

    fetchRoles();
  }, [visible, user]);

  // 转换布尔值为字符串
  const initialValues = user ? {
    ...user,
    isActive: user.isActive ? 'true' : 'false',
    isStaff: user.isStaff ? 'true' : 'false',
  } : undefined;
  
  return visible ? (
    <ModalForm
      title={user ? '编辑用户' : '新建用户'}
      visible={visible}
      onVisibleChange={onVisibleChange}
      modalProps={{
        destroyOnClose: true,
        afterClose: () => {
          setSelectedRoles([]);
          setRoleList([]);
        }
      }}
      initialValues={initialValues}
      onFinish={async (values: PatchedUserRequest) => {
        try {
          let userId: number;
          
          if (user) {
            // 更新用户
            await api.accounts.accountsUsersPartialUpdate({
              id: user.id,
              patchedUserRequest: values,
            });
            userId = user.id;
            message.success('更新成功');
          } else {
            // 创建新用户
            if (!values.password) {
              message.error('密码不能为空');
              return false;
            }
            const newUser = await api.accounts.accountsUsersCreate({
              userRequest: values as any,
            });
            userId = newUser.id;
            message.success('创建成功');
          }

          // 更新用户角色
          try {
            await api.accounts.accountsUsersPartialUpdate({
              id: userId,
              patchedUserRequest: {
                groups: selectedRoles.map(id => parseInt(id))
              }
            });
            message.success('角色更新成功');
          } catch (error) {
            message.error('角色更新失败');
            return false;
          }

          onSuccess();
          return true;
        } catch (error) {
          message.error(user ? '更新失败' : '创建失败');
          return false;
        }
      }}
    >
      <ProFormText
        name="username"
        label="用户名"
        placeholder="请输入用户名"
        rules={[
          {
            required: true,
            message: '用户名不能为空',
          },
        ]}
        disabled={!!user}
      />
      <ProFormText.Password
        name="password"
        label="密码"
        placeholder={user ? "不修改请留空" : "请输入密码"}
        rules={[
          {
            required: !user,
            message: '密码不能为空',
          },
        ]}
      />
      <ProFormText
        name="email"
        label="邮箱"
        placeholder="请输入邮箱"
        rules={[
          {
            type: 'email',
            message: '请输入有效的邮箱地址',
          },
        ]}
      />
      <ProFormText
        name="firstName"
        label="名"
        placeholder="请输入名"
      />
      <ProFormText
        name="lastName"
        label="姓"
        placeholder="请输入姓"
      />
      <ProFormSelect
        name="isActive"
        label="状态"
        fieldProps={{
          id: 'form_isActive'
        }}
        valueEnum={{
          'true': '启用',
          'false': '禁用',
        }}
      />
      <ProFormSelect
        name="isStaff"
        label="管理员权限"
        fieldProps={{
          id: 'form_isStaff'
        }}
        valueEnum={{
          'true': '是',
          'false': '否',
        }}
      />
      <div style={{ margin: '24px 0' }}>
        <div style={{ marginBottom: '8px' }}>角色</div>
        <Transfer
          dataSource={roleList}
          titles={['可选角色', '已选角色']}
          targetKeys={selectedRoles}
          onChange={setSelectedRoles}
          render={item => item.title}
          loading={loading}
          listStyle={{
            width: 250,
            height: 300,
          }}
        />
      </div>
    </ModalForm>
  ) : null;
};

export default UserForm;
